#include <signal.h>
#include <unistd.h>

#include "args.h"
#include "log.h"
#include "monitor.h"
#include "setter.h"

static void signal_handler(int sig) {
    keep_running = 0;
}

static void run(int argc, char *argv[], arguments args) {
    maxpwr = args.maxpwr;
    if (strcmp(args.logfile, "-") == 0) {
        log_file = stdout;
    } else {
        log_file = fopen(args.logfile, "a");
    }

    log_verbose = args.verbose;

    log_out_v("KRATOS", "Kratos called\n");
    for (int i = 0; i < argc; ++i) {
        log_out_v("KRATOS", "\targv[%i]: %s\n", i, argv[i]);
    }

    monitor("wlp2s0", setter, args.interval);

    if (strcmp(args.logfile, "-") != 0) {
        fclose(log_file);
    }

}


int main(int argc, char *argv[]) {
    signal(SIGINT, signal_handler);
    signal(SIGTERM, signal_handler);

    arguments args;

    args.verbose = 0;
    args.logfile = "-";
    args.interval = 5;
    args.maxpwr = 15;

    argp_parse(&argp, argc, argv, 0, 0, &args);

    int fork_result = 0;

    if (args.daemon) {
        fork_result = fork();
    }

    if (fork_result == 0)
        run(argc, argv, args);

    return 0;
}
